home *** CD-ROM | disk | FTP | other *** search
- Path: oxy.rust.net!usenet
- From: pgunn@mail.cbf.com (Paul Gunn)
- Newsgroups: comp.lang.c++
- Subject: Re: Constructor Exceptions
- Date: Thu, 04 Jan 1996 17:03:00 GMT
- Organization: Rust Net - High Speed Internet in Detroit 810-642-2276
- Message-ID: <4ch1c3$bsm@oxy.rust.net>
- References: <4bud9g$pv5@oxy.rust.net> <4cbhcl$kst@dawn.mmm.com> <4ce68n$8u4@sundog.tiac.net>
- NNTP-Posting-Host: pgunn.cbf.com
- X-Newsreader: Forte Agent .99c/32.126
-
- page@tiac.net (Chris Page) wrote:
-
-
- >:> I use Microsoft Visual C++, and have been gradually making use of
- >:> exceptions in my code. I'm interested in using exceptions in my
- >:> constructor code, but according to a MS article, when an exception is
- >:> thrown from a constructor on a heap object, the memory will not be
- >:> freed.
- >
- >:> Is this behavior parculiar to the Microsoft implementation or is it
- >:> generally the case?
- >
- >:It is not generally the case. Compilers that adhere to the standard
- >:will produce code that does not leak memory in this way.
- >
- >Sure, they'll clean up 'this', but the programmer is responsible for
- >any and all heap memory allocated within the body of constructor.
-
- Here is an excerpt from the Visual C++ 2.1 documentation. It seems to
- indicate that 'this' will not be cleaned up.
-
- >
- Throwing an exception in a constructor is tricky, however, because the
- memory for the object itself has already been allocated by the time
- the constructor is called. There is no simple way to deallocate the
- memory occupied by the object from within the constructor for that
- object. Thus, you will find that throwing an exception in a
- constructor will result in the object remaining allocated. For a
- discussion of how to detect objects in your program that have not been
- deallocated, see the article Diagnostics: Detecting Memory Leaks.
- If you are performing operations in your constructor that can fail, it
- might be a better idea to put those operations into a separate
- initialization function rather than throwing an exception in the
- constructor. That way, you can safely construct the object and get a
- valid pointer to it. Then, you can call the initialization function
- for the object. If the initialization function fails, you can delete
- the object directly.
- <
-
- What do you think?
-
-
-
-